package com.tedu.mybatis.controller;

import com.tedu.mybatis.mapper.UserInfoMapper;
import com.tedu.mybatis.pojo.UserInfo;
import com.tedu.mybatis.utils.SqlSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author blue sky
 * @version 1.0
 * @description TODO
 * @date 2023/4/29 12:52
 */

@Slf4j
@Controller
public class UserController {

    private UserInfoMapper userInfoMapper;

    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        log.info("处理注册请求");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        //判断当前注册信息是否合法(不为空)
        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty() ||
                nickname == null || nickname.isEmpty() ||
                ageStr == null || ageStr.isEmpty()
        ) {
            try {
                log.error("当前注册信息为空");
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        //获取sql的会话对象sqlSession，是MyBatis提供的操作数据库的对象
        try (
                SqlSession sqlSession = SqlSessionUtil.getSqlSession()
        ) {
            //获取UserInfoMapper的代理实现类对象
            userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);

            //检测用户是否已注册
            UserInfo userInfoByName = userInfoMapper.getUserInfoByName(username);
            if (userInfoByName != null) {
                log.error("您已经注册过,请登录");
                response.sendRedirect("/have_user.html");
                return;
            }

            //注册用户,执行insertSQL语句
            UserInfo userInfo = new UserInfo(username, password, nickname, Integer.parseInt(ageStr));
            int row = userInfoMapper.insertUser(userInfo);

            if (row > 0) {
                log.info("注册成功!");
                response.sendRedirect("/reg_success.html");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        log.info("处理登陆请求");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //判断当前登陆信息是否合法(不为空)
        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty()
        ) {
            try {
                log.error("当前登陆信息为空");
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }


        try (
                SqlSession sqlSession = SqlSessionUtil.getSqlSession()
        ) {
            userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
            UserInfo userInfoByName = userInfoMapper.getUserInfoByName(username);

            //如果一个结果都没查到,说明没有该账户,登录信息有误
            if (userInfoByName == null) {
                log.error("账号不存在");
                response.sendRedirect("/login_fail.html");
                return;
            }
            //如果查到结果,就判断登陆密码是否正确
            if (!userInfoByName.getPassword().equals(password)) {
                log.error("密码错误!");
                response.sendRedirect("/login_fail.html");
                return;
            }

            log.info("登陆成功!");
            response.sendRedirect("/login_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request, HttpServletResponse response) {
        try (
                SqlSession sqlSession = SqlSessionUtil.getSqlSession()
        ) {
            userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);

            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>ID</td>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("<td>操作</td>");
            pw.println("</tr>");

            List<UserInfo> users = userInfoMapper.getAllUserInfo();
            for (UserInfo user : users) {
                int id = user.getId();
                pw.println("<tr>");
                pw.println("<td>" + id + "</td>");
                pw.println("<td>" + user.getUsername() + "</td>");
                pw.println("<td>" + user.getPassword() + "</td>");
                pw.println("<td>" + user.getNickname() + "</td>");
                pw.println("<td>" + user.getAge() + "</td>");
                pw.println("<td><a href = \"/deleteUser?id=" + id + "\">删除</a></td>");
                pw.println("</tr>");
            }

            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        log.info("执行删除操作");

        //从用户列表那里获取要删除的id
        String id = request.getParameter("id");
        try (
                SqlSession sqlSession = SqlSessionUtil.getSqlSession()
        ) {
            userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
            userInfoMapper.deleteUserById(Integer.parseInt(id));

            response.sendRedirect("/userList");
            log.info("删除用户成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
